package com.xframe.event.bus.core.config;

import cn.hutool.core.util.ObjectUtil;
import com.xframe.event.bus.core.annotation.ReceiveMsgArgs;
import com.xframe.event.bus.core.annotation.XReceiveMsg;
import com.xframe.event.bus.core.msg.BaseMsgReceive;
import com.xframe.event.bus.core.msg.ConnectFactory;
import com.xframe.event.bus.core.msg.MessageSender;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Log4j2
//@Component
public class EventRunner implements ApplicationRunner, InitializingBean, ApplicationContextAware {

    @Autowired
    private ConnectInfoBean configBean;

    private ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if(ObjectUtil.isEmpty(configBean) || ObjectUtil.isEmpty(configBean.getConnectInfo())){
            log.info("MQ配置为空");
            return;
        }
        ConnectFactory.createConnection(configBean.getConnectInfo());
        MessageSender.init();
        String[] names = applicationContext.getBeanNamesForAnnotation(XReceiveMsg.class);
        for(int i = 0; i < names.length; i++){
            BaseMsgReceive bean = (BaseMsgReceive)applicationContext.getBean(names[i]);
            if(bean != null){
                XReceiveMsg[] receiveMsgs = bean.getClass().getAnnotationsByType(XReceiveMsg.class);
                if (receiveMsgs.length == 0) {
                    continue;
                }
                bean.init(new ReceiveMsgArgs(receiveMsgs[0]));
            }
        }
        log.info("MQ init OK");
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
